#ifndef TCPMGR_H
#define TCPMGR_H

#include <QObject>
#include <QTcpSocket>
#include "global.h"
#include "signleton.h"
#include "userdata.h"
#include <memory>
class TcpMgr : public QObject, public Signleton<TcpMgr>, public std::enable_shared_from_this<TcpMgr>
{
    Q_OBJECT
    friend class Signleton<TcpMgr>;

public:
    ~TcpMgr();
public slots:
    void slot_tcp_connect(ServerInfo);
    void slot_send_data(ReqId reqId, QByteArray data);
signals:
    // 建立连接
    void sig_con_success(bool success);
    // 发送数据
    void sig_send_data(ReqId reqId, QByteArray data);
    //切换聊天页面
    void sig_switch_chatdlg();
    // 登录失败
    void sig_login_failed(int);
    // 用户搜索结果
    void sig_user_search(std::shared_ptr<SearchInfo> si);
    // 同意对方添加好友
    void sig_authRsp(std::shared_ptr<AuthRsp>);
    // 收到好友申请
    void sig_friendApply(std::shared_ptr<AddFriendApply>);
    // 对方同意添加好友
    void sig_addAuthFriend(std::shared_ptr<AuthInfo>);
    // 收到新文本消息
    void sig_hasNewTextMessage(std::shared_ptr<TextChatData>);

private:
    QTcpSocket _socket;
    QString _host;
    uint _port;
    QByteArray _buffer;
    bool _b_recv_pending;
    quint16 _message_id;
    quint16 _message_len;
    QMap<ReqId, std::function<void(ReqId id, int len, QByteArray data)>> _handlers;

private:
    TcpMgr();
    void initHandlers();
    void handleMsg(ReqId id, int len, QByteArray data);
};

#endif // TCPMGR_H
